using System.Collections.Concurrent;
using WebRtcProject.Models;

namespace WebRtcProject.Services
{
    public class UserService : IUserService
    {
        private readonly ConcurrentDictionary<string, User> _users = new();
        private readonly ConcurrentDictionary<string, string> _connectionIdToUserId = new();
        private readonly ILogger<UserService> _logger;

        public UserService(ILogger<UserService> logger)
        {
            _logger = logger;
        }

        public async Task<User> CreateUserAsync(string name, string connectionId)
        {
            var user = new User
            {
                Id = Guid.NewGuid().ToString(),
                Name = name,
                ConnectionId = connectionId,
                JoinedAt = DateTime.UtcNow,
                IsOnline = true
            };

            _users[user.Id] = user;
            _connectionIdToUserId[connectionId] = user.Id;
            
            _logger.LogInformation("Created user {UserId} with name {UserName}", user.Id, name);
            return await Task.FromResult(user);
        }

        public async Task<User?> GetUserAsync(string userId)
        {
            _users.TryGetValue(userId, out var user);
            return await Task.FromResult(user);
        }

        public async Task<User?> GetUserByConnectionIdAsync(string connectionId)
        {
            if (_connectionIdToUserId.TryGetValue(connectionId, out var userId))
            {
                return await GetUserAsync(userId);
            }
            return null;
        }

        public async Task<List<User>> GetAllUsersAsync()
        {
            return await Task.FromResult(_users.Values.ToList());
        }

        public async Task<bool> UpdateUserAsync(User user)
        {
            if (_users.ContainsKey(user.Id))
            {
                _users[user.Id] = user;
                _logger.LogInformation("Updated user {UserId}", user.Id);
                return true;
            }
            return false;
        }

        public async Task<bool> DeleteUserAsync(string userId)
        {
            if (_users.TryRemove(userId, out var user))
            {
                _connectionIdToUserId.TryRemove(user.ConnectionId, out _);
                _logger.LogInformation("Deleted user {UserId}", userId);
                return true;
            }
            return false;
        }

        public async Task<bool> SetUserOnlineStatus(string userId, bool isOnline)
        {
            if (_users.TryGetValue(userId, out var user))
            {
                user.IsOnline = isOnline;
                _logger.LogInformation("Set user {UserId} online status to {IsOnline}", userId, isOnline);
                return true;
            }
            return false;
        }
    }
} 